import 'package:flutter/material.dart' hide TabBar;
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/tabBar/kq_tabs.dart';

import '../../config/kq_pad_global.dart';
import '../../resources/kq_pad_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import '../tagView/kq_number_tag_view.dart';
import 'kq_number_tab.dart';

/// 指示器类型
enum PadIndicatorType {
  ///下划线
  underline,

  ///圆形背景
  roundBg
}

/// 通用 TabBar
///
/// @author 周卓
///
class KqPadTabBar extends StatefulWidget {
  /// 指示器类型，0：下划线，1：圆形背景
  final PadIndicatorType indicatorType;

  /// 支持器大小
  final TabBarIndicatorSize? indicatorSize;

  /// TabController
  final TabController? tabController;

  /// Tab数据，包括标题和角标，以及是否显示角标
  final List<PadTabDataEntity> items;

  /// 自定义TabBar右侧控件，比如管理Tab的菜单
  final Widget? customTabRightView;

  /// 是否可水平滚动，否则均分
  final bool scrollable;

  /// Tab切换回调
  final ValueChanged<int>? onTap;

  /// TabBar左右两边间距，默认0
  final double tabBarHorizontalMargin;

  /// 文字颜色和下划线颜色处理器，下划线颜色跟随选中的文字颜色，如果不设置，默认使用[_KqPadTabBarState._defaultTextColorBuilder]
  final Color? Function(
          PadIndicatorType indicatorType, bool selected, Color defColor)?
      textColorBuilder;

  /// 文字颜色和下划线颜色处理器，下划线颜色跟随选中的文字颜色，如果不设置，默认使用[_KqPadTabBarState._defaultUnderlineColorBuilder]
  final Color? Function(PadIndicatorType indicatorType, Color defColor)?
      underlineColorBuilder;

  /// 字体大小处理器，如果不设置，默认使用[_KqPadTabBarState._defaultFontSizeBuilder]
  final double Function(PadIndicatorType indicatorType, bool selected)?
      fontSizeBuilder;

  /// 字体加粗处理器，如果不设置，默认使用[_KqPadTabBarState._defaultFontSizeBuilder]
  final FontWeight Function(PadIndicatorType indicatorType, bool selected)?
      fontWeightBuilder;

  /// Tab背景颜色，针对 [PadIndicatorType.roundBg] 类型，选中时的颜色，默认跟随主题亮色
  final Color? roundBgColor;

  /// 角标最大数字，超过显示"[tagMaxNumber]+"，默认99
  final int tagMaxNumber;

  /// 是否隐藏底部分割线
  final bool hideDivider;

  /// 底部分割线颜色
  final Color? dividerColor;

  /// 默认选中位置，默认0，仅在[tabController]没传时生效
  final int initialIndex;

  /// 背景颜色
  final Color? backgroundColor;

  /// 指示器左右padding;TabBarIndicatorSize最好设置成tab
  final double? indicatorHorizontalPadding;

  const KqPadTabBar(
      {Key? key,
      required this.items,
      this.tabController,
      this.indicatorType = PadIndicatorType.underline,
      this.indicatorSize,
      this.textColorBuilder,
      this.underlineColorBuilder,
      this.customTabRightView,
      this.fontSizeBuilder,
      this.fontWeightBuilder,
      this.tagMaxNumber = 99,
      this.initialIndex = 0,
      this.roundBgColor,
      this.tabBarHorizontalMargin = 0,
      this.backgroundColor,
      this.scrollable = false,
      this.hideDivider = false,
      this.dividerColor,
      this.indicatorHorizontalPadding,
      this.onTap})
      : super(key: key);

  @override
  _KqPadTabBarState createState() => _KqPadTabBarState();
}

class _KqPadTabBarState extends State<KqPadTabBar>
    with TickerProviderStateMixin {
  /// 默认字体大小处理器
  double _defaultFontSizeBuilder(
      PadIndicatorType indicatorType, bool selected) {
    if (indicatorType == PadIndicatorType.underline) {
      //underline
      return 7.dm;
    } else {
      //roundBg
      return 6.dm;
    }
  }

  FontWeight _defaultFontWeightBuilder(
      PadIndicatorType indicatorType, bool selected) {
    return FontWeight.normal;
  }

  /// 默认文字颜色处理器
  Color _defaultTextColorBuilder(
      PadIndicatorType indicatorType, bool selected, Color defColor) {
    if (indicatorType == PadIndicatorType.underline) {
      //underline
      return selected
          ? (KqPadThemeManager.instance.getConfig().commonConfig.mainColor ??
              KqPadThemeColors.bgBlue)
          : defColor;
    } else {
      //roundBg
      return selected ? KqPadThemeColors.textWhite : defColor;
    }
  }

  /// 默认下划线颜色处理器
  Color _defaultUnderlineColorBuilder(
      PadIndicatorType indicatorType, Color defColor) {
    return defColor;
  }

  @override
  Widget build(BuildContext context) {
    TabBarIndicatorSize indicatorSize = widget.indicatorSize ??
        (widget.indicatorType == PadIndicatorType.underline
            ? TabBarIndicatorSize.tab
            : TabBarIndicatorSize.label);
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: widget.tabBarHorizontalMargin),
      child: ClipRect(
        child: Stack(
          children: [
            TabBar(
                //选中的文字颜色
                labelColor: _textColor(true),
                //选中的文字样式
                labelStyle: TextStyle(
                    color: _textColor(true),
                    fontSize: _fontSize(true),
                    fontWeight: _fontWeigth(false)),
                //未选中的文字颜色
                unselectedLabelColor: _textColor(false),
                //未选中的文字样式
                unselectedLabelStyle: TextStyle(
                    color: _textColor(false),
                    fontSize: _fontSize(false),
                    fontWeight: _fontWeigth(false)),
                controller: widget.tabController ??
                    TabController(
                        initialIndex: widget.initialIndex,
                        length: widget.items.length,
                        vsync: this),
                isScrollable: widget.scrollable || KqPadGlobal.tabBarScrollable,
                indicatorWeight:
                    widget.indicatorType == PadIndicatorType.underline
                        ? 1.dm
                        : 0,
                indicatorSize: indicatorSize,
                indicatorPadding: widget.indicatorHorizontalPadding != null
                    ? EdgeInsets.symmetric(
                        horizontal: widget.indicatorHorizontalPadding!)
                    : (widget.indicatorType == PadIndicatorType.underline ||
                            indicatorSize == TabBarIndicatorSize.tab
                        ? EdgeInsets.zero
                        : EdgeInsets.symmetric(horizontal: -15.dm)),
                labelPadding: _scrollable()
                    ? EdgeInsets.symmetric(horizontal: 15.dm)
                    : EdgeInsets.zero,
                onTap: widget.onTap,
                tabs: widget.items
                    .map((e) => KqPadNumberTab(
                          text: e.title,
                          top: 0,
                          numberBuilder: () => e.hideNumber
                              ? Container()
                              : KqPadNumberTagView(
                                  number: e.number,
                                  minSize: 8.dm,
                                  fontSize: 5.dm,
                                  backgroundColor: _tagBgColor(),
                                  max: widget.tagMaxNumber,
                                ),
                        ))
                    .toList(),
                indicator: widget.indicatorType == PadIndicatorType.underline
                    ? UnderlineTabIndicator(
                        borderSide: BorderSide(
                            width: 2.0,
                            // 下划线颜色
                            color: _underlineColor()),
                      )
                    : BoxDecoration(
                        //圆形背景颜色
                        color: _roundBgColor(),
                        borderRadius: BorderRadius.all(Radius.circular(3.dm)))),
            if (widget.indicatorType == PadIndicatorType.underline &&
                !widget.hideDivider)
              Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: KqPadDivider.normal(height: 2.0))
          ],
        ),
      ),
    );
  }

  _scrollable() {
    return widget.scrollable || KqPadGlobal.tabBarScrollable;
  }

  /// 文字颜色
  _fontSize(bool selected) {
    return widget.fontSizeBuilder == null
        ? _defaultFontSizeBuilder(widget.indicatorType, selected)
        : widget.fontSizeBuilder!(widget.indicatorType, selected);
  }

  _fontWeigth(bool selected) {
    return widget.fontWeightBuilder == null
        ? _defaultFontWeightBuilder(widget.indicatorType, selected)
        : widget.fontWeightBuilder!(widget.indicatorType, selected);
  }

  /// 文字颜色
  _textColor(bool selected) {
    return widget.textColorBuilder == null
        ? _defaultTextColorBuilder(
            widget.indicatorType, selected, KqPadThemeColors.textBlack85)
        : widget.textColorBuilder!(
                widget.indicatorType, selected, KqPadThemeColors.textBlack85) ??
            KqPadThemeColors.textBlack85;
  }

  /// 下划线颜色
  _underlineColor() {
    return widget.underlineColorBuilder == null
        ? _defaultUnderlineColorBuilder(
            widget.indicatorType,
            KqPadThemeManager.instance.getConfig().commonConfig.mainColor ??
                KqPadThemeColors.bgBlue)
        : widget.underlineColorBuilder!(
                widget.indicatorType,
                KqPadThemeManager.instance.getConfig().commonConfig.mainColor ??
                    KqPadThemeColors.bgBlue) ??
            KqPadThemeManager.instance.getConfig().commonConfig.mainColor ??
            KqPadThemeColors.bgBlue;
  }

  /// 角标背景颜色
  _tagBgColor() {
    return widget.indicatorType == PadIndicatorType.underline
        ? _underlineColor()
        : _roundBgColor();
  }

  /// 圆背景颜色
  _roundBgColor() {
    return widget.roundBgColor ??
        (KqPadThemeManager.instance.getConfig().commonConfig.mainColor ??
            KqPadThemeColors.textBlue);
  }
}

/// Tab数据填充
class PadTabDataEntity {
  /// 标题
  String title;

  /// 选中时显示的标题，仅对[KqPadShadowTabBar]有用
  String? selectedTitle;

  /// 数字角标
  int number;

  /// 是否隐藏角标
  bool hideNumber;

  /// 额外数据，备用
  dynamic extraData;

  PadTabDataEntity(this.title,
      {this.number = 0,
      this.hideNumber = false,
      this.extraData,
      this.selectedTitle});
}
